import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import VueCookies from 'vue-cookies'
import { ElMessageBox } from 'element-plus'
import { deepClone } from '@/utils'
import _ from 'lodash'

const cookie: any = VueCookies
const BaseUrl = '/api'
const IAMtokenKey = 'X-Auth-Token'
export class Request {
  instance: AxiosInstance
  baseConfig: AxiosRequestConfig = { baseURL: BaseUrl, timeout: 60000, headers: { IAMtokenKey: null } }

  constructor(config: AxiosRequestConfig) {
    this.instance = axios.create(Object.assign(this.baseConfig, config))
    this.instance.interceptors.request.use(
      (config: any) => {
        let AuthToken = cookie.get('token')
        if (AuthToken) {
          config.headers['token'] = AuthToken
        }
        return config
      },
      (err: any) => {
        this.openElMessageBox()
        return Promise.reject(err)
      }
    )

    this.instance.interceptors.response.use(
      (res: AxiosResponse) => {
        let IAMtoken = cookie.get(IAMtokenKey)
        let userToken = cookie.get('userToken')
        if (res.headers.Authorization != userToken && res.headers.userExpiredTime) {
          let time = new Date(parseInt(res.headers!.userExpiredTime))
          cookie.set('userToken', res.headers.Authorization, time)
        }
        if (res.headers.IAMtokenKey != IAMtoken && res.headers.expiredTime) {
          let time = new Date(parseInt(res.headers!.expiredTime))
          cookie.set(IAMtokenKey, res.headers.IAMtokenKey, time)
        }
        return res
      },
      (err: any) => {
        this.openElMessageBox('请求错误')
        return Promise.reject(err.response)
      }
    )
  }

  openElMessageBox = (title: string = '温馨提示', message: string = '系统未知错误，请联系管理员！') => {
    ElMessageBox.alert(message, title, {
      confirmButtonText: 'OK'
    })
  }

  // 定义请求方法
  public request(config: AxiosRequestConfig): Promise<AxiosResponse> {
    return this.instance.request(config)
  }

  //响应是AxiosResponse类型，AxiosResponse.data是T类型
  public get<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
    return this.instance.get(url, config || { params: data })
  }

  public post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
    return this.instance.post(url, data, config)
  }

  public put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
    return this.instance.put(url, data, config)
  }

  public delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
    return this.instance.delete(url, config)
  }
}

// 默认导出Request实例
export default new Request({})
